# python 2.7
# auto generate level config
import json
import random
import math

allToies = []

def readFileByPath(path):
    with open(path,'r') as file:
        jsondata = json.load(file)
    return jsondata

def writeFileToPath(path,data):
    with open(path,'w') as file:
        json.dump(data,file)

def createRandom(min,max):
    return math.floor(random.random() * (max - min) + min)

def fmtStr(originfmstr,datas):
    return originfmstr.format(*datas)

def generateRandomLevel(levels):
    global allToies
    c = len(allToies)

    maxLen = c
    result = {}
    minLen = 2
    d = 0.1

    for i in range(levels):
        curCount = int(math.floor(((maxLen - d * levels - minLen) / (levels * levels)) * (i * i) + d * i + minLen))

        curLevelToyNames = []
        tempToies = allToies[:]

        print(fmtStr("cueLevle is {0},curCount is {1}",[i,curCount]))
        
        random.shuffle(tempToies)

        for m in range(curCount):
            randomIndex = int(createRandom(0,len(tempToies)))
            print(randomIndex)
            if len(tempToies) == 0:
                # fmstr = "curlevel is {0} and curCount is {1} tempToies len is {2}".format(i,curCount,len(tempToies))
                res = fmtStr("curlevel is {0} and curCount is {1} tempToies len is {2}",[i,curCount,len(tempToies)])
                print(res)
                break

            targetValue = tempToies.pop(randomIndex)
            formatValue = "targetValue is {}".format(targetValue)
            print(formatValue)
            curLevelToyNames.append(targetValue)
        path = fmtStr("../Assets/StreamingAssets/Levels/level{0}.json",[i + 1])
        result['toys'] = curLevelToyNames
        writeFileToPath(path,result)




def main():
    jd = readFileByPath('../Assets/StreamingAssets/Config/allToy.json')

    if jd is not None and isinstance(jd["levels"],list):
        global allToies
        allToies = jd["levels"]
        totalLevels = 300
        generateRandomLevel(totalLevels)
    
def  test():
    arr = [10,20,30,40,50]
    arrCopy = arr[:]


if __name__ == "__main__":
    main()
     

    



    